<script setup lang="ts">
  import { CaretBottom, CaretRight } from '@element-plus/icons-vue'
  import { onMounted, ref } from 'vue'
  import { getOrderDetailFeeProjectList } from '@/api/order'
  import CostDetail from '@/views/order/ocost/components/CostDetail.vue'
  import FeeApplyCheckDialog from '../fee-apply-check-dialog/FeeApplyCheckDialog.vue'
  import FeeApplyUpdate from '../fee-apply-update/FeeApplyUpdate.vue'
  import { Cost } from './types'
  import { ElPagination } from 'element-plus'

  const props = defineProps({
    showAddServiceFeeWidthSpare: {
      type: Boolean,
      required: true,
    },
    orderId: {
      type: String,
      required: true,
    },
    orderNo: {
      type: String,
      required: true,
    },
    detail: {
      type: Object,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'updated'): void
  }>()

  // 表格数据
  const tableData = ref<Array<Cost>>([])

  // 列表总条数
  const total = ref(0)

  // 分页配置
  const pagination = ref({
    limit: 4,
    page: 1,
  })

  // 获取费用项目列表
  const getOrFeeProjectList = async () => {
    const res = await getOrderDetailFeeProjectList(pagination.value, props.orderId)
    tableData.value = res.data.data.rows
    total.value = Number(res.data.data.total)
    if (total.value >= 1) {
      activeNames.value.push('cost_list')
    }
  }

  // 费用id
  const costId = ref('')

  // 费用详情弹窗状态
  const costDetailModalVisible = ref(false)

  // 查看费用详细
  const handleViewCostDetail = (n: string) => {
    costDetailModalVisible.value = true
    costId.value = n
  }

  // 打开的面板
  const activeNames = ref([''])

  /**
   * 表格更新事件
   */
  const onUpdateTableData = () => {
    getOrFeeProjectList()
    emits('updated')
  }

  // 合计
  const getSummaries = (param) => {
    const arr = ['qty', 'priceTotal', 'customerUndertakePriceTotal', 'networkUndertakePriceTotal']
    const { columns, data } = param

    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index == 0) {
        sums[index] = '合计'
        return
      }
      if (!arr.includes(column.property)) {
        return
      }
      const values = data.map((item) => Number(item[column.property]))

      if (!values.every((value) => Number.isNaN(value))) {
        const valuesTotal = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        sums[index] = `${column.property == 'qty' ? '' : '￥'}${
          column.property == 'qty' ? valuesTotal : valuesTotal.toFixed(2)
        }`
      } else {
        sums[index] = ''
      }
    })
    return sums
  }
  const updateRef = ref(false)
  // 编辑
  const handleFeetEdit = (row) => {
    updateRef.value.onShowDrawer(row.id)
  }

  onMounted(() => {
    getOrFeeProjectList()
  })

  defineExpose({
    getOrFeeProjectList,
  })
</script>

<template>
  <div>
    <el-collapse v-model="activeNames">
      <el-collapse-item name="cost_list">
        <template #title>
          <div
            style="
              box-sizing: border-box;
              padding: 0 16px;
              display: flex;
              gap: 5px;
              align-items: center;
            "
          >
            <el-icon>
              <template v-if="activeNames.includes('cost_list')">
                <CaretBottom />
              </template>
              <template v-else>
                <CaretRight />
              </template>
            </el-icon>
            <span>服务费用({{ total }})</span>

            <!--@click.stop=""是为了解决点击申请费用按钮会展开面板-->
            <fee-apply-check-dialog
              :work-id="props.orderId"
              @click.stop=""
              @update="onUpdateTableData"
            >
              <HPlainButton v-if="showAddServiceFeeWidthSpare" :padding-lr="6" :height="22"
                >申请服务费用</HPlainButton
              >
            </fee-apply-check-dialog>
          </div>
        </template>
        <div style="box-sizing: border-box; padding: 0 16px">
          <el-table
            resizable
            :data="tableData"
            stripe
            :border="true"
            show-summary
            :summary-method="(val) => getSummaries(val)"
          >
            <!-- 序号 -->
            <el-table-column
              show-overflow-tooltip
              label="序号"
              fixed="left"
              min-width="50"
              :align="'center'"
            >
              <template #default="i">
                {{ i.$index + 1 }}
              </template>
            </el-table-column>

            <!-- 状态 -->
            <el-table-column prop="state" label="状态" width="83" fixed="right">
              <template #default="scope">
                <HStatus v-if="scope.row.status == 1" type="warning">待审核</HStatus>
                <HStatus v-if="scope.row.status == 2" type="success">已通过</HStatus>
                <HStatus v-if="scope.row.status == 3" type="error">已驳回</HStatus>
                <HStatus v-if="scope.row.status == 4" type="info">已撒回</HStatus>
                <HStatus v-if="scope.row.status == 5" type="info">已取消</HStatus>
              </template>
            </el-table-column>

            <!-- 费用单号 -->
            <el-table-column
              show-overflow-tooltip
              fixed="left"
              prop="feeNo"
              label="费用单号"
              min-width="160"
            >
              <template #default="scope">
                <HLink @click="handleViewCostDetail(scope.row.id)">
                  {{ scope.row.feeNo }}
                </HLink>
              </template>
            </el-table-column>

            <!-- 结算类型 -->
            <el-table-column
              show-overflow-tooltip
              prop="settlementType"
              label="结算类型"
              width="100"
            />

            <!-- 费用名称 -->
            <el-table-column show-overflow-tooltip prop="feeProject" label="费用名称" width="100" />

            <!-- 公里数 -->
            <el-table-column show-overflow-tooltip prop="kilometers" label="公里数" width="100">
              <template #default="{ row }">
                {{ row.kilometersList.join('、') }}
              </template>
            </el-table-column>

            <!-- 数量 -->
            <el-table-column show-overflow-tooltip prop="qty" label="数量" width="100" />

            <!-- 公司承担单价 -->
            <el-table-column show-overflow-tooltip prop="price" label="公司承担单价" width="150">
              <template #default="scope"> ￥{{ (scope.row.price || 0).toFixed(2) }} </template>
            </el-table-column>

            <!-- 收取客户单价 -->
            <el-table-column
              show-overflow-tooltip
              prop="customerUndertakePrice"
              label="收取客户单价"
              width="150"
            >
              <template #default="scope">
                ￥{{ (scope.row.customerUndertakePrice || 0).toFixed(2) }}
              </template>
            </el-table-column>

            <!-- 支付网点单价 -->
            <el-table-column
              show-overflow-tooltip
              prop="networkUndertakePrice"
              label="支付网点单价"
              width="150"
            >
              <template #default="scope">
                ￥{{ (scope.row.networkUndertakePrice || 0).toFixed(2) }}
              </template>
            </el-table-column>

            <!-- 公司承担总费用 -->
            <el-table-column
              show-overflow-tooltip
              prop="priceTotal"
              label="公司承担总费用"
              width="150"
            >
              <template #default="scope"> ￥{{ (scope.row.priceTotal || 0).toFixed(2) }} </template>
            </el-table-column>

            <!-- 收取客户总费用 -->
            <el-table-column
              show-overflow-tooltip
              prop="customerUndertakePriceTotal"
              label="收取客户总费用"
              width="150"
            >
              <template #default="scope">
                ￥{{ (scope.row.customerUndertakePriceTotal || 0).toFixed(2) }}
              </template>
            </el-table-column>

            <!-- 支付网点总费用 -->
            <el-table-column
              show-overflow-tooltip
              prop="networkUndertakePriceTotal"
              label="支付网点总费用"
              width="150"
            >
              <template #default="scope">
                ￥{{ (scope.row.networkUndertakePriceTotal || 0).toFixed(2) }}
              </template>
            </el-table-column>

            <!-- 申请人员 -->
            <el-table-column show-overflow-tooltip prop="applyEmp" label="申请人员" width="120" />

            <!-- 申请时间 -->
            <el-table-column show-overflow-tooltip prop="createTime" label="申请时间" width="150" />

            <!-- 审核时间 -->
            <el-table-column show-overflow-tooltip prop="reviewTime" label="审核时间" width="150" />

            <!-- 操作 -->
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="scope">
                <HLink
                  v-if="props.detail.status != 5 && props.detail.settlementStatus != 2"
                  @click="handleFeetEdit(scope.row)"
                  >编辑</HLink
                >
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 12px; display: flex; justify-content: flex-end">
            <el-pagination
              v-model:current-page="pagination.page"
              layout="total, prev, pager, next, jumper"
              :total="total"
              background
              :page-size="4"
              @current-change="getOrFeeProjectList"
            />
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <fee-apply-update
      ref="updateRef"
      :work-id="props.orderId"
      :work-no="props.orderNo"
      @update="onUpdateTableData"
    />
    <CostDetail v-model="costDetailModalVisible" :fee-id="costId" />
  </div>
</template>

<style lang="scss">
  .check_btn {
    color: #e69103;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }
</style>
